//
//  AiRoleItemView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/4/1.
//

import SwiftUI
import Kingfisher

/**
 *  api 站点 item
 */
struct ApiSitesItemView: View {
    @StateObject var viewModel = ApiSitesItemViewModel()
    @State private var showFullScreen = false //预览图片
    @State private var selectedIndex = 0
    
    var bean:ApiSitesBean
    
    var body: some View {
        // 目前contextMenu 会失效，先不处理，后续看下有没有更好的解决方案
        ZStack {
            Menu {
                commonMenuContent
            } label: {
                contentView
            }
        }.contextMenu {
            commonMenuContent
        }.fullScreenCover(isPresented: $showFullScreen) {
            FullScreenMediaView(mediaItems: viewModel.mediaItems, currentIndex: $selectedIndex)
        }
    }
    
    
}

//内容试图
extension ApiSitesItemView {
    private var contentView: some View {
        HStack(alignment:.center) {
            AvatarImageView(url: bean.avatar ?? "", size: 50)
                .contentShape(Rectangle())
            VStack(alignment:.leading) {
                Text(bean.name ?? "").font(.system(size: 14, weight: .medium)).foregroundColor(.bgNormalText)
                Text(bean.content ?? "")
                    .font(.system(size: 12))
                    .foregroundColor(.bgNormalText4).lineLimit(2)
                    .multilineTextAlignment(.leading)  // 明确设置多行文本对齐方式
            }
        }.frame(maxWidth: .infinity,alignment:.leading)
            .padding(EdgeInsets(top: 12, leading: 15, bottom: 12, trailing: 15))
            .background(.bgItem)
            .cornerRadius(15)
    }
}

//菜单
extension ApiSitesItemView {
    // 将菜单内容抽离为一个计算属性，方便复用
    private var commonMenuContent: some View {
        Group {
            Button("网站跳转"){
                guard let url = URL(string: bean.url ?? "") else {
                    showToast("暂未配置网站地址")
                    return
                }
                // 打开 Safari
                UIApplication.shared.open(url)
            }
            Button("教程"){
                guard let tutorial = bean.tutorial, !tutorial.isEmpty else {
                    showToast("暂未配置教程")
                    return
                }
                viewModel.mediaItems = [MediaItem(type: MediaType.networkImage(tutorial, tutorial, false))]
                showFullScreen = true
            }
            Button("复制API") {
                showToast("已复制API")
                copyClipboard(bean.host)
            }
        }
    }
    
}

class ApiSitesItemViewModel : BaseViewModel {
    @Published var mediaItems: [MediaItem] = []
}

#Preview {
    ApiSitesItemView(bean:ApiSitesBean())
}
